// 子窗口组件
import { Button } from "antd";
import { useEffect, useState } from "react";

// 子窗口组件：支持与多个父窗口实例通信
const CommunicateTab = () => {
  const [windowId, setWindowId] = useState(null);
  const [messages, setMessages] = useState([]);

  // 发送消息给父窗口
  const sendToParent = (data) => {
    if (window.opener) {
      window.opener.postMessage(
        { 
          type: 'CHILD_RESPONSE', 
          data: { 
            ...data,
            windowId
          } 
        },
        '*'
      );
      setMessages(prev => [...prev, { ...data, time: new Date() }]);
    }
  };

  // 接收父窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      const { type, data } = e.data;
      const { windowId: receivedWindowId } = data || {};
      
      if (type === 'INIT_DATA') {
        setWindowId(receivedWindowId);
        console.log(`接收初始化数据 (窗口ID: ${receivedWindowId}):`, data.data);
        setMessages(prev => [...prev, {
          type: 'init',
          message: data.data.message,
          time: new Date()
        }]);
      } else if (type === 'PARENT_COMMAND' && receivedWindowId === windowId) {
        console.log(`接收父窗口命令 (窗口ID: ${receivedWindowId}):`, data.command);
        setMessages(prev => [...prev, {
          type: 'command',
          message: data.command,
          time: new Date()
        }]);
        
        // if (data.command === 'refreshData') {
        //   // 执行刷新操作并响应
        //   sendToParent({ 
        //     status: 'refreshed', 
        //     data: { timestamp: new Date().getTime() },
        //     windowId
        //   });
        // }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [windowId]);

  return (
    <div>
      <h3>可通信的子标签页 (ID: {windowId || '未初始化'})</h3>
      <div style={{ marginTop: 10, padding: 15, border: '1px solid #e8e8e8', borderRadius: 4 }}>
        <h4>通信记录</h4>
        {messages.length > 0 ? (
          <ul>
            {messages.map((msg, index) => (
              <li key={index}>
                {msg.type === 'init' ? 
                  `初始化: ${msg.message}` : 
                  `命令: ${msg.message} (时间: ${msg.time.toLocaleTimeString()})`
                }
              </li>
            ))}
          </ul>
        ) : (
          <p>等待接收消息...</p>
        )}
      </div>
      <Button 
        type="primary" 
        onClick={() => sendToParent({ 
          message: '来自子窗口的消息', 
          windowId
        })}
        disabled={!windowId}
      >
        发送消息给父窗口
      </Button>
    </div>
  );
};
export default CommunicateTab;